package org.jeecg.modules.sggg.controller;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.sggg.entity.*;
import org.jeecg.modules.sggg.service.ISgBlutdruckRecordService;
import org.jeecg.modules.sggg.service.ISgGlucoseRecordService;
import org.jeecg.modules.sggg.service.ISgLipidRecordService;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "血糖、血压测量数据管理")
@RestController
@RequestMapping("/healthyCabin")
@Slf4j
public class SgHealthyCabinController extends JeecgController<SgMember, ISgMemberService> {

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private SgBlutdruckRecordController sgBlutdruckRecordController;

    @Autowired
    private SgGlucoseRecordController sgGlucoseRecordController;

    @Autowired
    private SgLipidRecordController sgLipidRecordController;

    /**
     * 检查设备在线状态
     *
     * @param data
     * @return
     */
    @PostMapping("/sh05/sendHeartBeat")
    public Result<String> sendHeartBeat(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-检查设备在线状态" + data);
        return Result.ok("success");
    }

    /**
     * 获取设备广告
     *
     * @param data
     * @return
     */
    @PostMapping("/sh05/getBannerByMac")
    public Result<String> getBannerByMac(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-获取设备广告" + data);
        return Result.ok("success");
    }

    /**
     * 获取设备LOGO
     *
     * @param data
     * @return
     */
    @PostMapping("/sh05/getLogoByMac")
    public Result<String> getLogoByMac(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-获取设备LOGO" + data);
        return Result.ok("success");
    }

    /**
     * 获取微信二维码URL
     *
     * @param data
     * @return
     */
   /* @PostMapping("/sh05/getQRCodeUrl")
    public JSONObject getQRCodeUrl(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-获取微信二维码URL" + data);
        JSONObject object = new JSONObject();
        object.put("code", 5);
        object.put("msg", "获取失败");
        return object;
    }*/

    /**
     * 获取用户信息(扫码体检)
     *
     * @param data
     * @return
     */
    @PostMapping("/sh05/getUserWeixinBySequences")
    public Result<String> getUserWeixinBySequences(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-获取用户信息(扫码体检)" + data);
        return Result.ok("success");
    }

    /**
     * 获取用户信息(手机号体检)
     *
     * @param data
     * @return
     */
    @PostMapping("/sh05/getUserByPhone")
    public Result<String> getUserByPhone(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-获取用户信息(手机号体检)" + data);
        return Result.ok("success");
    }

    /**
     * 获取用户信息(身份证)
     *
     * @param data
     * @return
     */
    @PostMapping("/sh05/getUserByIdcard")
    public JSONObject getUserByIdcard(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-获取用户信息(身份证)" + data);
        JSONObject object = (JSONObject) JSON.toJSON(data);
        JSONObject returnData = new JSONObject();
        List<SgMember> sgMember = sgMemberService.list(new QueryWrapper<SgMember>().eq("id_card", object.getString("idcard")));
        if (sgMember.size() < 1) {
            returnData.put("code", 5);
            returnData.put("msg", "没有找到该记录");
        } else if (sgMember.size() >= 1) {
            JSONObject data_ = new JSONObject();
            returnData.put("code", 2);
            returnData.put("msg", "接口调用成功");
            data_.put("userName", sgMember.get(0).getName());
            data_.put("sex", sgMember.get(0).getSex().equals(0) ? 1 : 2);
            data_.put("birthday", sgMember.get(0).getBirthday());
            data_.put("idcard", sgMember.get(0).getIdCard());
            returnData.put("data", data_);
        }
        return returnData;
    }

    /**
     * 获取用户信息(卡号体检)
     *
     * @param data
     * @return
     */
    @PostMapping("/sh05/getUserByCardNo")
    public Result<String> getUserByCardNo(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-获取用户信息(卡号体检)" + data);
        return Result.ok("success");
    }

    /**
     * 检查手机或者身份证是否重复
     *
     * @param data
     * @return
     */
    @PostMapping("/sh05/checkPhoneByIdcard")
    public Result<String> checkPhoneByIdcard(@RequestBody Map<String, Object> data) {
        log.info("健康小屋-检查手机或者身份证是否重复" + data);
        return Result.ok("success");
    }

    /**
     * 上传体检数据
     *
     * @param map 体检数据
     * @return 不论过程是否成功，都返回成功
     */
    @PostMapping("/sh05/uploadData")
    public JSONObject uploadData(@RequestBody Map<String, Object> map) throws Exception {
        List<Object> data = (List<Object>) map.get("data");
        List<SgMember> sgMember = new ArrayList<>();
        for (Object data_ : data) {
            JSONObject object = (JSONObject) JSON.toJSON(data_);
            // 输出体检请求参数
            if (StringUtils.isNotBlank(object.getString("photoPath"))) {
                object.remove("photoPath");
                log.info("健康小屋-上传的体检数据" + object);
            } else {
                log.info("健康小屋-上传的体检数据" + object);
            }
            // 该用户是否存在
            if (StringUtils.isNotBlank(object.getString("idCard"))) {
                sgMember = sgMemberService.list(new QueryWrapper<SgMember>().eq("id_card", object.getString("idCard")));
            } else {
                sgMember = sgMemberService.list(new QueryWrapper<SgMember>().eq("phone", object.getString("phone")));
            }
            if (sgMember.size() == 1) {
                saveMemberData(sgMember.get(0), object);
            } else {
                log.info("==========没有该用户的数据，执行居民建档==========");
                SgMember member = PHR(object);
                saveMemberData(member, object);
                /* // 判断是否为三高患者
                if (StringUtils.isNotBlank(object.getString("heightPressureState")) || StringUtils.isNotBlank(object.getString("lowPressureState")) || StringUtils.isNotBlank(object.getString("bloodSugarState"))) {
                    if (
                            (Integer.parseInt(object.getString("heightPressureState")) != 5 || Integer.parseInt(object.getString("lowPressureState")) != 5)
                                    ||
                                    (Integer.parseInt(object.getString("bloodSugarState")) != 3)
                    ) {

                    }
                } */
            }
        }
        JSONObject object = new JSONObject();
        object.put("code", 2);
        object.put("msg", "success");
        return object;
    }


    /**
     * 保存用户体检数据
     *
     * @param sgMember 居民信息
     * @param object   体检数据
     */
    public void saveMemberData(SgMember sgMember, JSONObject object) throws Exception {
        log.info("==========保存用户体检数据==========");
        // 血压
        if (StringUtils.isNotBlank(object.getString("heightPressure"))) {
            SgBlutdruckRecord sgBlutdruckRecord = new SgBlutdruckRecord();
            sgBlutdruckRecord.setMemberId(sgMember.getId());
            sgBlutdruckRecord.setMeasuringTime(DateTime.now());
            sgBlutdruckRecord.setDeviceId(object.getString("factoryNumber"));
            sgBlutdruckRecord.setSysOrgCode(sgMember.getSysOrgCode());
            sgBlutdruckRecord.setSbpval(Double.valueOf(object.getString("heightPressure")));
            sgBlutdruckRecord.setDbpval(Double.valueOf(object.getString("lowPressure")));
            sgBlutdruckRecord.setHeartRate(Integer.valueOf(object.getString("pulse")));
            sgBlutdruckRecordController.add(sgBlutdruckRecord);
        }
        // 血糖
        if (StringUtils.isNotBlank(object.getString("bloodSugar"))) {
            SgGlucoseRecord sgGlucoseRecord = new SgGlucoseRecord();
            sgGlucoseRecord.setMemberId(sgMember.getId());
            sgGlucoseRecord.setMeasuringTime(DateTime.now());
            sgGlucoseRecord.setDeviceId(object.getString("factoryNumber"));
            sgGlucoseRecord.setSysOrgCode(sgMember.getSysOrgCode());
            sgGlucoseRecord.setGluval(Double.valueOf(object.getString("bloodSugar")));
            sgGlucoseRecord.setPhase(Integer.valueOf(object.getString("bloodSugarType")));
            sgGlucoseRecordController.add(sgGlucoseRecord);
        }
        // 血脂
        if (StringUtils.isNotBlank(object.getString("cholesterol"))) {
            SgLipidRecord sgLipidRecord = new SgLipidRecord();
            sgLipidRecord.setMemberId(sgMember.getId());
            sgLipidRecord.setMeasuringTime(DateTime.now());
            sgLipidRecord.setDeviceId(object.getString("factoryNumber"));
            sgLipidRecord.setSysOrgCode(sgMember.getSysOrgCode());
            sgLipidRecord.setTotalCholesterol(Double.valueOf(object.getString("cholesterol")));
            if (StringUtils.isNotBlank(object.getString("triglycerides"))) {
                sgLipidRecord.setTriglyceride(Double.valueOf(object.getString("triglycerides")));
            }
            if (StringUtils.isNotBlank(object.getString("lowLipoprotein"))) {
                sgLipidRecord.setLdlc(Double.valueOf(object.getString("lowLipoprotein")));
            }
            if (StringUtils.isNotBlank(object.getString("heightLipoprotein"))) {
                sgLipidRecord.setHdlc(Double.valueOf(object.getString("heightLipoprotein")));
            }
            sgLipidRecordController.add(sgLipidRecord);
        }
        try {
            double weight = object.getDouble("weight");
            double height = object.getDouble("height");
            double bmi = weight / (height * height);
            sgMember.setBmi(bmi);
            sgMemberService.updateById(sgMember);
        } catch (Exception e) {
            log.error("健康小屋-保存用户bmi数据时报错：" + e.getMessage());
        }
    }

    /**
     * 居民建档
     *
     * @param object 体检数据
     * @return 居民信息
     */
    public SgMember PHR(JSONObject object) throws Exception {
        SgMember member = new SgMember();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmm");
        if (StringUtils.isNotBlank(object.getString("userName"))) {
            member.setName(object.getString("userName"));
        }
        member.setPhone(object.getString("phone"));
        if (StringUtils.isNotBlank(object.getString("idCard"))) {
            member.setIdCard(object.getString("idCard"));
        }
        if (StringUtils.isNotBlank(object.getString("birthday"))) {
            member.setBirthday(dateFormat.parse(object.getString("birthday")));
        }
        member.setSex(object.getString("sex").equals("1") ? 0 : 1);
        if (StringUtils.isNotBlank(object.getString("height"))) {
            member.setHeight(Double.valueOf(object.getString("height")).intValue());
        }
        if (StringUtils.isNotBlank(object.getString("weight"))) {
            member.setWeight(Double.valueOf(object.getString("weight")).intValue());
        }
        if (StringUtils.isNotBlank(object.getString("hwBmi"))) {
            member.setBmi(Double.valueOf(object.getString("hwBmi")));
        }
        member.setSysOrgCode("A01");

        //#region 设置预警值

        // 舒张压
        member.setDbpvalMax(90.0);
        member.setDbpvalMin(60.0);
        // 收缩压
        member.setSbpvalMax(140.0);
        member.setSbpvalMin(90.0);
        // 血糖
        member.setSugarMax(6.1);
        member.setSugarMin(1.1);
        // 血脂
        member.setBloodMax(5.2);
        member.setBloodMin(0.0);
        // 体脂
        member.setBodyfatMax(14.0);
        member.setBodyfatMin(6.0);

        //#endregion

        sgMemberService.save(member);
        return member;
    }
}
